<template>
  <div class="app-container">
    <el-form
      class="search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      @keyup.enter="handleQuery"
    >
      <el-form-item label="物料编码" prop="fMaterialId">
        <el-input v-model="queryParams.fMaterialId" placeholder="请输入物料编码" clearable />
      </el-form-item>
      <el-form-item label="物料名称" prop="fMaterialName">
        <el-input v-model="queryParams.fMaterialName" placeholder="请输入物料名称" clearable />
      </el-form-item>
      <!-- 在此添加搜索项 -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查找</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="body-container">
      <div class="operate-container body-button">
        <el-button type="primary" icon="Plus" @click="handleCreate">新增</el-button>
        <el-upload
          action=""
          :before-upload="beforeUpload"
          :on-change="handleFileChange"
          accept=".xls,.xlsx"
          :show-file-list="false"
          class="upload"
        >
          <el-button type="primary" icon="Plus">导入</el-button>
        </el-upload>
        <el-button type="info" @click="downloadExcel" icon="Download">下载导入模板</el-button>
        <el-button type="primary" icon="Plus" @click="handlePass">提交TPM</el-button>
      </div>
      <div class="table-container">
        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="60" type="index" align="center">
            <template #default="scoped">
              <span>{{ (queryParams.current - 1) * queryParams.size + scoped.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="物料编码"
            prop="fMaterialId"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            label="物料名称"
            prop="fMaterialName"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            label="规格型号"
            prop="fMaterialModel"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column label="单位" prop="fUnitId" align="center" show-overflow-tooltip />
          <el-table-column label="数量" prop="fQty" align="center" show-overflow-tooltip />
          <!-- 在此添加其他列 -->
          <el-table-column min-width="150" fixed="right" label="操作" align="center">
            <template #default="scoped">
              <el-button link type="primary" icon="Edit" @click="handleEdit(scoped.row)">
                编辑
              </el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scoped.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <dc-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.size"
      @pagination="getData"
    />
  </div>
  <!-- 弹出新增 -->
  <el-dialog v-model="open" title="新增" width="1200">
    <el-table v-loading="loading" :data="addDataList">
      <el-table-column label="序号" width="60" type="index" align="center">
        <template #default="scoped">
          <span>{{ (queryParams.current - 1) * queryParams.size + scoped.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" prop="fMaterialId" align="center" show-overflow-tooltip />
      <el-table-column label="物料名称" prop="fMaterialName" align="center" show-overflow-tooltip />
      <el-table-column
        label="规格型号"
        prop="fMaterialModel"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="单位" prop="fUnitId" align="center" show-overflow-tooltip />
      <el-table-column label="数量" prop="fQty" align="center" show-overflow-tooltip />
      <!-- 在此添加其他列 -->
      <el-table-column min-width="150" fixed="right" label="操作" align="center">
        <template #default="scoped">
          <el-button link type="primary" icon="Delete" @click="handleAddDelete(scoped.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="addDataListSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择TPM -->
  <el-dialog
    v-model="dialogVisible"
    title="提交TPM"
    :close-on-click-modal="false"
    width="30%"
    align-center
    class="audit"
  >
    <el-form>
      <el-form-item label="选择组织">
        <dc-select
          v-model="formData.orgId"
          objectName="org"
          placeholder="请选择"
          @change="handleOrgIdChange"
          clearable
        />
      </el-form-item>
      <el-form-item label="单据类型">
        <el-select v-model="formData.fBillTypeDictId" clearable placeholder="请选择单据类型">
          <el-option-group v-for="group in groupedOptions" :key="group.id" :label="group.label">
            <el-option
              v-for="option in group.children"
              :key="option.id"
              :label="option.label"
              :value="option.id"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="选择TPM">
        <template #default="scoped">
          <dc-select-user
            v-model="formData.tpmOperatorId"
            placeholder="请选择TPM"
            returnType="string"
            :multiple="false"
            :multiple-limit="1"
          />
        </template>
        <!--        <el-select v-model="formData.fTpm" placeholder="请选择">-->
        <!--          <el-option-->
        <!--            v-for="item in tpmOptions"-->
        <!--            :key="item.id"-->
        <!--            :label="item.fname"-->
        <!--            :value="item.fnumber"-->
        <!--          />-->
        <!--        </el-select>-->
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleTpmSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新增或者编辑 -->
  <el-dialog v-model="openRow" :title="title" destroy-on-close append-to-body>
    <el-form ref="formRef" :model="formData" label-width="120px" :rules="rules">
      <el-form-item label="物料编码" prop="fMaterialId">
        <el-select
          v-model="formData.fMaterialId"
          placeholder="物料编码"
          :remote-method="remoteMethod"
          @change="changeMaterial"
          reserve-keyword
          filterable
          remote
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.fmaterialId"
            :label="item.fnumber"
            :value="item.fmaterialId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="fMaterialName">
        <el-select
          v-model="formData.fMaterialName"
          placeholder="物料名称"
          :remote-method="remoteMethod2"
          @change="changeMaterial"
          reserve-keyword
          filterable
          remote
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.fmaterialId"
            :label="item.fname"
            :value="item.fmaterialId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号" prop="fMaterialModel">
        <el-input v-model="formData.fMaterialModel" placeholder="规格型号" disabled />
      </el-form-item>
      <el-form-item label="单位" prop="fUnitId">
        <el-select v-model="formData.fUnitId" placeholder="单位" style="width: 240px">
          <el-option
            v-for="item in unitOptions"
            :key="item.bizKey"
            :label="item.bizValue"
            :value="item.bizKey"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="fQty">
        <el-input-number
          v-model="formData.fQty"
          :min="0"
          placeholder="数量"
          controls-position="right"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ComponentName">
import { reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import Api from '@/api/index'; // 根据实际路径调整导入
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus';
import { deepClone } from '@/utils/util';

const { proxy } = getCurrentInstance();

// 数据字典
const { DC_BILL_TYPE } = proxy.useCache([{ key: 'DC_BILL_TYPE' }]);

const pageData = reactive({
  loading: false,
  queryParams: {
    current: 1,
    size: 10,
  },
  dataList: [],
  total: 0,
  open: false,
  addDataList: [],
  dialogVisible: false,
  formData: {
    orgId: '100006',
  },
  tpmOptions: [],
  selectionList: [],
  openRow: false,
  title: '',
  formRef: null,
  rules: {
    fMaterialId: [
      {
        required: true,
        message: '请选择物料编码',
        trigger: 'blur',
      },
    ],
    fMaterialName: [
      {
        required: true,
        message: '请选择物料名称',
        trigger: 'blur',
      },
    ],
    fMaterialModel: [
      {
        required: true,
        message: '请选择物料',
        trigger: 'blur',
      },
    ],
    fUnitId: [
      {
        required: true,
        message: '请选择单位',
        trigger: 'blur',
      },
    ],
    fQty: [
      {
        required: true,
        message: '请输入数量',
        trigger: 'blur',
      },
    ],
  },
  materialOptions: [],
  unitOptions: [],
});

const {
  loading,
  queryParams,
  dataList,
  total,
  open,
  addDataList,
  dialogVisible,
  formData,
  tpmOptions,
  selectionList,
  openRow,
  title,
  formRef,
  rules,
  materialOptions,
  unitOptions,
} = toRefs(pageData);

onMounted(async () => {
  await getOptions();
  getData();
  getTpm();
});

const downloadExcel = () => {
  // 文件的 HTTP 链接
  const excelUrl =
    'https://static.eastwinbip.com/static/file/%E6%89%A7%E8%A1%8C%E7%94%B3%E8%AF%B7%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF1.xlsx';

  // 创建一个 a 标签用于下载
  const link = document.createElement('a');
  link.href = excelUrl;
  link.download = 'example.xlsx'; // 自定义下载文件名

  // 将 a 标签添加到文档并触发点击
  document.body.appendChild(link);
  link.click();

  // 移除 a 标签
  document.body.removeChild(link);
};

const getData = async () => {
  try {
    loading.value = true;
    const res = await Api.pdp.dcErporder.erpList(queryParams.value);
    const { code, data } = res.data;
    if (code === 200) {
      dataList.value = data.records;
      total.value = data.total;
    }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const getTpm = async () => {
  try {
    loading.value = true;
    const res = await Api.pdp.erpSelect.tpm(formData.value);
    const { code, data } = res.data;
    if (code === 200) {
      tpmOptions.value = data;
    }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const handleOrgIdChange = value => {
  formData.value.fTpm = '';
  getTpm();
};

const handleSelectionChange = selection => {
  selectionList.value = selection;
};
const handlePass = () => {
  if (selectionList.value.length > 0) {
    dialogVisible.value = true;
  } else {
    ElMessage({
      message: '至少选择一条数据',
      type: 'warning',
    });
  }
};
const handleTpmSubmit = async () => {
  // 差一个接口 问芝林 压力他 让快点
  const form = {
    ...formData.value,
    dcErpOrderItemList: selectionList.value,
  };

  const res = await Api.pdp.dcErporder.orderSubmitTpmList(form);
  const { code, data } = res.data;
  if (code == 200) {
    proxy.$message({
      type: 'success',
      message: '操作成功!',
    });
    dialogVisible.value = false;
    getData();
  }
};

const handleDelete = row => {
  const ids = row.id;
  proxy
    .$confirm(`确定将“[${ids}]”数据删除?`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => Api.pdp.erpSelect.delete({ ids }))
    .then(() => {
      proxy.$message({
        type: 'success',
        message: '操作成功!',
      });
      getData();
    });
};

const handleQuery = () => {
  queryParams.value.current = 1;
  getData();
};

const resetQuery = () => {
  queryParams.value = {
    current: 1,
    size: 10,
  };
  proxy.resetForm('queryRef');
  getData();
};

const beforeUpload = file => {
  const isExcel =
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    // 使用 Element Plus 的消息提示
    proxy.$message.error('只能上传 Excel 文件!');
  }
  return isExcel;
};
// 确认解析xlsx 赋值
const handleFileChange = file => {
  open.value = true;
  const reader = new FileReader();
  reader.onload = e => {
    const ab = e.target.result;
    const workbook = XLSX.read(ab, { type: 'array' });

    // 获取第一个工作表的内容
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

    // 格式化数据  需要什么加什么
    addDataList.value = jsonData.slice(1).map(row => ({
      fMaterialId: row[0],
      fMaterialName: row[1],
      fMaterialModel: row[2],
      fUnitId: row[3],
      fQty: row[4],
    }));
  };
  reader.readAsArrayBuffer(file.raw);
};

const addDataListSubmit = async () => {
  const res = await Api.pdp.dcErporder.orderSubmitList(addDataList.value);
  const { code, msg } = res.data;
  if (code === 200) {
    proxy.$message({
      type: 'success',
      message: '操作成功!',
    });
    open.value = false;
    getData();
  }
};

const handleAddDelete = row => {
  proxy
    .$confirm(`确定将数据删除?`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => (addDataList.value = addDataList.value.filter(item => item !== row)))
    .then(() => {
      proxy.$message({
        type: 'success',
        message: '操作成功!',
      });
      getData();
    });
};

// 分组逻辑：通过 parentId 将数据分组
const groupedOptions = computed(() => {
  const topLevelGroups = DC_BILL_TYPE.value.filter(item => item.parentId === '1870707615783387138');
  // 获取预测单分组
  const forecastGroup = topLevelGroups.filter(group => group.label === '预测单')[0];
  // 返回预测单相关的子项
  return [
    {
      id: forecastGroup.id,
      label: forecastGroup.label,
      dictKey: forecastGroup.dictKey,
      children: DC_BILL_TYPE.value.filter(item => item.parentId === forecastGroup.id),
    },
  ];
});

const getOptions = async () => {
  const res2 = await Api.pdp.dcErporder.dict();
  const { code: code2, data: data2 } = res2.data;
  if (code2 === 200) {
    unitOptions.value = data2.计量单位;
  }
};

const remoteMethod = async query => {
  if (query) {
    const params = { fnumber: query };
    const res = await Api.pdp.erpSelect.materials(params);
    const { code, data } = res.data;
    if (code === 200) {
      materialOptions.value = data;
    }
  }
};

const remoteMethod2 = async query => {
  if (query) {
    const params = { fname: query };
    const res = await Api.pdp.erpSelect.materials(params);
    const { code, data } = res.data;
    if (code === 200) {
      materialOptions.value = data;
    }
  }
};

const changeMaterial = id => {
  const option = materialOptions.value.find(item => item.fmaterialId === id);
  formData.value.fMaterialId = option?.fnumber || null;
  formData.value.fMaterialName = option?.fname || null;
  formData.value.fMaterialModel = option?.fspecification || null;
  formData.value.fUnitId = option?.funitId || null;
};

// 处理新增
const handleCreate = () => {
  title.value = '新增';
  openRow.value = true;
};

// 处理编辑
const handleEdit = row => {
  formData.value = deepClone(row);
  title.value = '编辑';
  openRow.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  formData.value = {};
  title.value = '';
  openRow.value = false;
};

// 提交表单
const submitForm = () => {
  proxy.$refs['formRef'].validate(async valid => {
    if (valid) {
      const res = await Api.pdp.dcErporder.orderSubmit(formData.value);
      const { code } = res.data;
      if (code === 200) {
        proxy.$message({ type: 'success', message: '申请成功' });
        getData();
        closeDialog();
      }
    }
  });
};
</script>
<style lang="scss">
.audit {
  .el-dialog__body {
    height: auto !important;
  }
}
</style>
<style lang="scss" scoped>
.body-button {
  display: flex;
  justify-content: flex-start !important;
  gap: 16px;
  .upload {
    display: flex;
  }
}
</style>
